<template>
  <!-- 订单管理 -->
  <div class="dashboard-container">
    <SearchTable :show-pagination="false">
      <template slot="header">
        <el-row style="width: 100%">
          <el-input
            style="width: 300px"
            @input="searchKeyWord"
            clearable
            placeholder="请输入收货人搜索关键词"
            v-model="keyWord"
          ></el-input>
          <span class="search-title">订单状态:</span>
          <el-select
            v-model="activeStatus"
            placeholder="请选择"
            @change="onStatusChange"
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-row>
        <!-- <el-button type="primary" @click="addStore">注册用户</el-button> -->
      </template>
      <template>
        <!-- 订单表格 -->
        <el-table
          default-expand-all
          :border="true"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
        >
          <!-- 展开 -->
          <el-table-column type="expand">
            <template slot-scope="props">
              <div class="address-container">
                <el-table
                  :border="true"
                  ref="multipleTable"
                  :data="props.row.orderdetailsList"
                  tooltip-effect="dark"
                  style="width: 100%"
                >
                  <el-table-column
                    align="center"
                    label="商品主图"
                    prop="pictures"
                    width="120"
                  >
                    <template v-slot="{ row }">
                      <img
                        :src="JSON.parse(row.pictures)[0]"
                        alt
                        style="width: 80px; height: auto; cursor: pointer"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="商品名称"
                    prop="product_name"
                    width="120"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="category_name"
                    label="商品分类"
                    width="120"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="product_description"
                    label="商品描述"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="stock"
                    label="库存(件)"
                    width="120"
                  ></el-table-column>

                  <el-table-column
                    align="center"
                    width="160"
                    prop="quantity"
                    label="商品数量"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="price"
                    label="价格(元)"
                  ></el-table-column>
                  <el-table-column align="center" prop="price" label="金额(元)">
                    <template v-slot="{ row }">{{
                      parseFloat(row.price * row.quantity).toFixed(2)
                    }}</template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>

          <!-- 展开 -->
          <el-table-column
            align="center"
            label="收货人"
            prop="recipient_name"
            width="120"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="recipient_phone"
            label="收货号码"
            width="120"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="address"
            label="收货地址"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="created_at"
            label="订单创建时间"
            width="160"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="updated_at"
            label="订单更新时间"
            width="160"
          ></el-table-column>
          <el-table-column
            align="center"
            width="100"
            prop="total_amount"
            label="总金额"
          ></el-table-column>
          <el-table-column
            v-if="!['3', '4', '5', '6'].includes(activeStatus)"
            align="center"
            width="140"
            label="操作"
          >
            <template v-slot="{ row }">
              <el-link
                v-if="+row.status == 2"
                style="margin-left: 10px"
                :underline="false"
                type="primary"
                @click="toDeliver(row)"
                >发货</el-link
              >

              <el-link
                v-if="row.status == 1"
                style="margin-left: 10px"
                :underline="false"
                type="danger"
                title="取消订单"
                @click="cancelOrder(row)"
                >取消</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </SearchTable>

    <!-- 弹框 -->
    <AddDialog
      :storeData="storeForm"
      :title="title"
      v-if="addVisible"
      :visible.sync="addVisible"
      @confirm="addStoreConfirm"
    ></AddDialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import SearchTable from "@/components/TableTemplate/SearchTable";
import {
  getAllOrdersByStatus,
  getAllOrderdetailsByOrderId,
  updateOrders,
  updateUserInfo,
} from "@/api/user";
import AddDialog from "./components/AddDialog";
export default {
  name: "Dashboard",
  components: {
    SearchTable,
    AddDialog,
  },
  data() {
    return {
      activeStatus: "1",
      statusList: [
        {
          label: "未支付",
          value: "1",
        },
        {
          label: "已支付",
          value: "2",
        },
        {
          label: "已发货",
          value: "3",
        },
        {
          label: "已完成",
          value: "4",
        },
        {
          label: "已退款",
          value: "5",
        },
        {
          label: "已取消",
          value: "6",
        },
      ],
      tableData: [],
      originTableData: [],
      addVisible: false,
      title: "注册用户",
      storeForm: {},
      imgDialogVisible: false,
      imgDialogData: [],
      keyWord: "",
      timer: null,
    };
  },
  mounted() {
    this.getAllOrdersByStatus();
  },
  computed: {
    ...mapGetters(["name", "token"]),
  },
  methods: {
    showImgDialog(storeImg) {
      this.imgDialogVisible = true;
      this.imgDialogData = storeImg;
    },
    updateOrders(order_id, status = 6, message = "确认取消订单吗？") {
      return new Promise((resolve) => {
        this.$confirm(`${message} 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const params = {
              order_id,
              status,
            };
            const res = await updateOrders(params);
            if (res.status === 0) {
              this.$message({
                type: "success",
                message: "操作成功",
              });
              this.getAllOrdersByStatus();
              resolve(true);
            } else {
              this.$message.error("操作失败！");
              resolve(false);
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
            resolve(false);
          });
      });
    },
    toDeliver(row) {
      this.updateOrders(row.order_id, 3, "确认发货吗？");
    },
    cancelOrder(row) {
      this.updateOrders(row.order_id, 6, "确认取消未支付订单吗？");
    },
    onStatusChange() {
      this.getAllOrdersByStatus();
    },
    async getAllOrdersByStatus() {
      const { data: res } = await getAllOrdersByStatus(+this.activeStatus || 1);

      // 使用 Promise.all 等待所有异步操作完成
      const list =
        (await Promise.all(
          res.map(async (item) => {
            const { data: orderDetails } = await getAllOrderdetailsByOrderId(
              item.order_id
            );
            item.orderdetailsList = orderDetails;
            return item;
          })
        )) || [];

      this.tableData = list || [];
      this.originTableData = list || [];
    },
    searchKeyWord(keyWord) {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        //这里setTimeout用来防抖，也就是500ms内一直在输入，就会清除上次的定时器，就不会一直搜索，等输入完了之后才真正执行一次搜索，优化
        //先复原
        this.tableData = this.originTableData;
        //再过滤
        let arr = [];
        this.tableData.map((item) => {
          if (item.recipient_name.indexOf(keyWord) !== -1) {
            arr.push(item);
          }
        });
        this.tableData = arr;
      }, 500);
    },
    addStore() {
      this.title = "注册用户";
      this.addVisible = true;
      this.storeForm = {};
    },
    edit(row) {
      this.title = "编辑用户";
      this.addVisible = true;
      this.storeForm = row;
    },
    addStoreConfirm() {
      //刷新列表
      this.getAllOrdersByStatus();
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  width: 100%;
  height: 100%;
}
.link-list {
  .el-link {
    margin: 0 2px;
  }
}
.img-box {
  margin-left: 65px;
  width: 80px;
  height: 120px;
  display: block;
}
.search-title {
  margin: 0 12px;
}
</style>
